<?php
/**
 * Order
 * Created by Veyron
 * motto:现在的拼搏 为了更好的明天
 * day:  2020/1/21
 * Time: 17:14
 */

namespace app\common\business;
use app\common\lib\Snowflake;
use app\common\model\mysql\Order as OrderModel;
use app\common\model\mysql\OrderGoods;
use think\Exception;
use think\facade\Cache;

class Order extends BusBase
{
    public $model = null;
    public function __construct()
    {
        $this->model = new OrderModel();
    }

    /**
     * 创建订单
     * @param $data
     * @return array|bool
     * @throws Exception
     */
    public function save($data){
        //拿到一个订单号
        $workId  = rand(1, 1023);
        $orderId = Snowflake::getInstance()->setWorkId($workId)->id();
        //获取购物车数据 =》redis
        $cartObj = new Cart();
        $result = $cartObj->lists($data['user_id'], $data['ids']);
        if(!$result){
            return false;
        }

        $newResult = array_map(function ($v) use($orderId){
            $v['sku_id'] = $v['id'];
            unset($v['id']);
            $v['order_id'] = $orderId;
            return $v;
        }, $result);

        //统计订单总价
        $price = array_sum(array_column($result,'total_price'));
        $orderData = [
            'user_id'        => $data['user_id'],
            'order_id'       => $orderId,
            'total_price'    => $price,
            'address_id'     => $data['address_id'],
        ];

        //开启事务，订单、支付必须使用事务
        $this->model->startTrans();
        try {
            //新增 order
            $id = $this->add($orderData);
            if (!$id) {
                return false;
            }

            //新增 order_goods
            $orderGoodsResult = (new OrderGoods())->saveAll($newResult);

            if(!$orderGoodsResult){
                throw new Exception('order_goods表新增异常');
            }
            //goods_sku 更新
            $skuRes = (new GoodsSku())->updateStock($result);
            if(!$skuRes){
                throw new Exception('goods_sku表更新异常');
            }
            //goods 库存更新
            $goodsStock = [];
            foreach ($newResult as $v){
                if(isset($goodsStock[$v['goods_id']])){
                    $goodsStock[$v['goods_id']] += $v['num'];
                }else{
                    $goodsStock[$v['goods_id']] = $v['num'];
                }
            }
            $goodsRes = (new Goods())->updateStock($goodsStock);
            if(!$goodsRes){
                throw new Exception('goods表更新异常');
            }
            //删除购物车里面的商品
            $cartObj->deleteRedis($data['user_id'], $data['ids']);

            //把当前订单ID放入延迟队列中(添加队列), 定期检查订单是否支付（订单有效时间是20分钟，超过这个时间
            // 我们需要打这个订单取消,然后库存+操作）
            try{
                Cache::zAdd(config('redis.order_status_key'), time() + config('redis.order_expire'), $orderId);
            }catch (\Exception $e){
                // 记录日志，添加监控，异步根据监控内容处理
            }

            $this->model->commit();
            return ['id' => (string)$orderId];
        }catch (\Exception $e) {
            $this->model->rollback();
            return false;
        }

    }

    public function detail($data){
        //组合查询条件（$data中肯需要其他数据，所以查询条件需要重新组装）
        $condition = [
            'user_id'   => $data['user_id'],
            'order_id'  => $data['order_id'],
        ];
        try {
            $orders = $this->model->getByCondition($condition);
        }catch (\Exception $e){
            $orders = [];
        }
        if(!$orders){
            return [];
        }
        $orders = $orders->toArray();
        $order = !empty($orders) ? $orders[0] : [];
        if(empty($order)){
            return [];
        }

        $order['id'] = $order['order_id'];

        $order['consignee_info'] = '北京 海淀区 海淀一路 海淀大厦 小王 188xxxxxxx';
        // 根据订单id查询订单下的商品
        $orderGoods = (new OrderGoods())->getByOrderId($data['order_id']);

        $order['malls'] = $orderGoods;
        return $order;
    }

    public function checkOrderStatus(){
        //获取有序集合中 0-time()(当前时间)的集合
        $orderIds = Cache::zRangeByScore(config('redis.order_status_key'), 0, time());

        if(empty($orderIds)){
            return false;
        }
//        try {
//            $delRedis = Cache::zRem(config('redis.order_status_key'), $result[0]);
//        }catch (\Exception $e){
//            $delRedis = '';
//        }

//        $lists = $this->getInByIds($orderIds,['status'   => 1]);
        $orderGoodsLists = (new \app\common\business\OrderGoods())->getInByIds($orderIds);

        if($orderGoodsLists){
            $orderIdSting = implode(',', $orderIds);
            echo "订单id:$orderIdSting 在规定时间内没有完成支付，我们判定为无效订单删除".PHP_EOL;
//            $orderGoodsIds = array_column($orderGoodsLists, 'num', 'order_id');
            //第一部，根据订单ID 去数据库order表里获取这条数据，如果是  status = 1 (待支付) 修改为 status = 7 (已取消)
            //第二部，如果status改为7需要查询order_goods sku_id num ,sku表和 goods表需要加回来

//            if(!$orderIds){
//                return false;
//            }
//
//            //更新sku库存数据
//            //获取sku 库存信息
//            $sku_ids_key = array_column($orderGoodsLists, 'sku_id');
//            $skuInfo = (new GoodsSku())->getNormalInIds($sku_ids_key);
//
//            $sku_ids = [];
//            foreach ($orderGoodsLists as $sku){
//                if(isset($sku_ids[$sku['sku_id']])){
//                    $sku_ids[$sku['sku_id']] += $sku['num'];
//                }else{
//                    $sku_ids[$sku['sku_id']] = $sku['num'];
//                }
//
//            }
//
//              $skuInfo 和 $sku_ids 循环组装需要的 数据进行更新
                //todo ...
//            dump($orderGoodsLists);die;
//            $skuRes = (new GoodsSku())->updateStock($result);

            $this->model->saveAll($orderGoodsIds);
        }else{
            return false;
        }
        return true;
    }

}

